#!/usr/bin/env bash

# ==============================================
# XG加密工具 - 智能路径版 v3.0
# 特性：全自动脚本定位+交互式选择+安全执行
# ==============================================

# 颜色定义
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
MAGENTA='\033[1;35m'
CYAN='\033[1;36m'
NC='\033[0m'

# 全局变量
SCRIPT_NAME="xgencrypt.py"
declare -a FOUND_SCRIPTS
SELECTED_SCRIPT=""

# 检测系统类型
detect_os() {
    case "$(uname -s)" in
        Linux*)  OS="Linux" ;;
        Darwin*) OS="macOS" ;;
        CYGWIN*|MINGW*|MSYS*) OS="Windows" ;;
        *)       OS="Unknown" ;;
    esac
}

# 安全搜索函数（限制深度和数量）
smart_search() {
    echo -e "${CYAN}[+] 正在智能搜索 ${SCRIPT_NAME}...${NC}"
    
    # 根据系统类型调整搜索参数
    case "$OS" in
        "Linux"|"macOS")
            search_cmd="find / -type f -name ${SCRIPT_NAME} 2>/dev/null | head -50"
            ;;
        "Windows")
            search_cmd="find /mnt/* -maxdepth 4 -type f -name ${SCRIPT_NAME} 2>/dev/null | head -50"
            ;;
        *)
            search_cmd="find ~ -type f -name ${SCRIPT_NAME} 2>/dev/null | head -20"
            ;;
    esac

    # 执行搜索并处理结果
    while IFS= read -r path; do
        [[ -n "$path" ]] && FOUND_SCRIPTS+=("$path")
    done < <(eval "$search_cmd")

    # 添加当前目录检测
    [[ -f "./${SCRIPT_NAME}" ]] && FOUND_SCRIPTS+=("$(pwd)/${SCRIPT_NAME}")

    # 去重处理
    mapfile -t FOUND_SCRIPTS < <(printf '%s\n' "${FOUND_SCRIPTS[@]}" | sort -u)
}

# 交互式选择菜单
show_selector() {
    clear
    echo -e "${CYAN}"
    cat << "EOF"
  ██╗  ██╗ ██████╗     ███████╗ ██████╗██████╗ ██╗██████╗ ████████╗
  ╚██╗██╔╝██╔════╝     ██╔════╝██╔════╝██╔══██╗██║██╔══██╗╚══██╔══╝
   ╚███╔╝ ██║  ███╗    ███████╗██║     ██████╔╝██║██████╔╝   ██║   
   ██╔██╗ ██║   ██║    ╚════██║██║     ██╔══██╗██║██╔═══╝    ██║   
  ██╔╝ ██╗╚██████╔╝    ███████║╚██████╗██║  ██║██║██║        ██║   
  ╚═╝  ╚═╝ ╚═════╝     ╚══════╝ ╚═════╝╚═╝  ╚═╝╚═╝╚═╝        ╚═╝   
EOF
    echo -e "${NC}"
    echo -e " ${YELLOW}>> 找到 ${#FOUND_SCRIPTS[@]} 个可用脚本 <<${NC}"
    echo -e " ${GREEN}===================================================${NC}"
    
    # 显示可选项
    for i in "${!FOUND_SCRIPTS[@]}"; do
        dir_name=$(dirname "${FOUND_SCRIPTS[$i]}")
        printf " ${YELLOW}%2d.${NC} %-40s ${BLUE}(%s)${NC}\n" \
               $((i+1)) "${FOUND_SCRIPTS[$i]}" "${dir_name##*/}"
    done
    
    echo -e " ${GREEN}===================================================${NC}"
    echo -e " ${RED}  0. 手动输入路径${NC}"
    echo -e " ${RED} 99. 退出系统${NC}"
    echo -e " ${GREEN}===================================================${NC}"
}

# 安全选择函数
safe_selection() {
    while true; do
        read -p " 请选择脚本编号 [0-99]: " choice
        
        case "$choice" in
            0)
                read -p " 请输入完整路径: " custom_path
                if [[ -f "$custom_path" && "$custom_path" == *.py ]]; then
                    SELECTED_SCRIPT="$custom_path"
                    return 0
                else
                    echo -e "${RED}[!] 无效路径或非Python文件${NC}"
                fi
                ;;
            99)
                exit 0
                ;;
            *)
                if [[ "$choice" =~ ^[0-9]+$ ]] && \
                   (( choice >= 1 && choice <= ${#FOUND_SCRIPTS[@]} )); then
                    SELECTED_SCRIPT="${FOUND_SCRIPTS[$((choice-1))]}"
                    return 0
                else
                    echo -e "${RED}[!] 无效选择，请重新输入${NC}"
                fi
                ;;
        esac
    done
}

# 安全执行函数
safe_execute() {
    local action=$1
    
    # 验证脚本有效性
    if [[ ! -f "$SELECTED_SCRIPT" ]]; then
        echo -e "${RED}[!] 脚本不存在: $SELECTED_SCRIPT${NC}"
        return 1
    fi

    # 验证Python环境
    if ! command -v python3 &>/dev/null; then
        echo -e "${RED}[!] 未检测到Python3环境${NC}"
        return 1
    fi

    case "$action" in
        1|2|3|6)
            echo -e "${CYAN}[+] 执行操作 $action @ ${SELECTED_SCRIPT}${NC}"
            python3 "$SELECTED_SCRIPT" "$action"
            read -p "按回车键继续..."
            ;;
        4|7)
            echo -e "${MAGENTA}[+] 启动动态密钥生成器...${NC}"
            python3 "$SELECTED_SCRIPT" "$action"
            ;;
        5)
            if [[ "$OS" == "Windows" || "$OS" == "Linux" ]]; then
                echo -e "${CYAN}[+] 执行加密狗模拟...${NC}"
                python3 "$SELECTED_SCRIPT" 5
            else
                echo -e "${RED}[!] 此功能仅在Windows/Linux可用${NC}"
                read -p "按回车键继续..."
            fi
            ;;
        *)
            echo -e "${RED}[!] 无效操作码${NC}"
            return 1
            ;;
    esac
}

# 主菜单
main_menu() {
    while true; do
        clear
        echo -e "${CYAN}"
        echo -e " >> 当前使用脚本: ${BLUE}$SELECTED_SCRIPT${NC}"
        echo -e " ${GREEN}===================================================${NC}"
        echo -e " ${CYAN}1. iCloud密钥加密      5. 加密狗制作(PC only)${NC}"
        echo -e " ${CYAN}2. 哈希多次加密       6. 文本凯撒加密工具${NC}"
        echo -e " ${CYAN}3. 猴子算法加密       7. 动态数字密钥${NC}"
        echo -e " ${CYAN}4. 动态混合密钥       8. 重新选择脚本${NC}"
        echo -e " ${CYAN}0. 退出系统${NC}"
        echo -e " ${GREEN}===================================================${NC}"
        
        read -p " 请输入操作编号: " choice
        
        case "$choice" in
            1|2|3|4|5|6|7)
                safe_execute "$choice"
                ;;
            8)
                return 1  # 触发重新选择
                ;;
            0)
                exit 0
                ;;
            *)
                echo -e "${RED}[!] 无效选择${NC}"
                sleep 1
                ;;
        esac
    done
}

# 主流程
main() {
    detect_os
    
    while true; do
        # 搜索阶段
        FOUND_SCRIPTS=()
        smart_search
        
        # 如果没有找到脚本
        if [[ ${#FOUND_SCRIPTS[@]} -eq 0 ]]; then
            echo -e "${RED}[!] 未找到任何 ${SCRIPT_NAME} 脚本${NC}"
            read -p " 是否手动指定路径? [y/N]: " yn
            case "$yn" in
                [Yy]*)
                    show_selector
                    safe_selection
                    ;;
                *)
                    exit 1
                    ;;
            esac
        else
            # 选择阶段
            show_selector
            safe_selection
        fi
        
        # 主菜单阶段
        if main_menu; then
            continue  # 正常流程
        else
            continue  # 重新选择
        fi
    done
}

# 启动
main